package org.cbyyx.tc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.cbyyx.tc.constant.CommonConstant;
import org.cbyyx.tc.enums.ErrorCode;
import org.cbyyx.tc.exception.BusinessException;
import org.cbyyx.tc.mapper.ProductsMapper;
import org.cbyyx.tc.model.dto.productRequest.ProductCreateRequest;
import org.cbyyx.tc.model.dto.productRequest.ProductQueryRequest;
import org.cbyyx.tc.model.dto.productRequest.ProductUpdateRequest;
import org.cbyyx.tc.model.entity.Products;
import org.cbyyx.tc.model.vo.productResponse.ProductDetailVO;
import org.cbyyx.tc.model.vo.productResponse.ProductsVO;
import org.cbyyx.tc.service.ProductsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品服务实现类
 * 提供商品相关的业务逻辑实现，包括商品CRUD、库存管理、价格调整等功能
 *
 * @author cbyyx
 * @since 2025-4-27
 */
@Service
public class ProductsServiceImpl extends ServiceImpl<ProductsMapper, Products> implements ProductsService {

    /**
     * 创建商品
     *
     * @param request 商品创建请求参数，包含商品基本信息
     * @return Boolean 创建是否成功
     */
    @Override
    public Boolean createProduct(ProductCreateRequest request) {
        Products product = new Products();
        // 设置product属性
        return this.save(product);
    }

    /**
     * 获取商品详情
     *
     * @param id 商品ID
     * @return ProductDetailVO 商品详情视图对象
     */
    @Override
    public ProductDetailVO getProductDetail(Long id) {
        Products product = this.getById(id);
        return convertToDetailVO(product);
    }

    /**
     * 更新商品信息
     *
     * @param request 商品更新请求参数，包含需要更新的字段
     * @return Boolean 更新是否成功
     */
    @Override
    public Boolean updateProduct(ProductUpdateRequest request) {
        Products product = this.getById(request.getId());
        // 更新product属性
        return this.updateById(product);
    }

    /**
     * 更新商品库存
     *
     * @param id       商品ID
     * @param quantity 新的库存数量
     * @return Boolean 更新是否成功
     */
    @Override
    @Transactional
    public Boolean updateStock(Long id, Integer quantity) {
        return lambdaUpdate()
                .eq(Products::getId, id)
                .ge(Products::getStock, quantity) // 确保库存充足
                .set(Products::getStock, quantity)
                .update();
    }

    /**
     * 减少商品库存
     *
     * @param id       商品ID
     * @param quantity 减少的库存数量
     * @return Boolean 减少是否成功
     */
    @Override
    @Transactional
    public Boolean decreaseStock(Long id, Integer quantity) {
        return lambdaUpdate()
                .setSql("stock = stock - " + quantity)
                .eq(Products::getId, id)
                .ge(Products::getStock, quantity)
                .update();
    }

    /**
     * 增加商品库存
     *
     * @param id       商品ID
     * @param quantity 增加的库存数量
     * @return Boolean 增加是否成功
     */
    @Override
    @Transactional
    public Boolean increaseStock(Long id, Integer quantity) {
        return lambdaUpdate()
                .setSql("stock = stock + " + quantity)
                .eq(Products::getId, id)
                .update();
    }

    /**
     * 更新商品价格
     *
     * @param id    商品ID
     * @param price 新的价格
     * @return Boolean 更新是否成功
     */
    @Override
    public Boolean updatePrice(Long id, Long price) {
        return lambdaUpdate()
                .eq(Products::getId, id)
                .set(Products::getPrice, price)
                .update();
    }

    /**
     * 更新商品状态
     *
     * @param id     商品ID
     * @param status 新的状态
     * @return Boolean 更新是否成功
     */
    @Override
    public Boolean updateStatus(Long id, String status) {
        return lambdaUpdate()
                .eq(Products::getId, id)
                .set(Products::getStatus, status)
                .update();
    }

    /**
     * 删除商品
     *
     * @param id 商品ID
     * @return Boolean 删除是否成功
     */
    @Override
    public Boolean deleteProduct(Long id) {
        return this.removeById(id);
    }

    /**
     * 分页查询商品列表
     *
     * @param request 商品查询请求参数，包含分页和筛选条件
     * @return Page<ProductsVO> 商品分页列表视图对象
     */
    @Override
    public Page<ProductsVO> listProducts(ProductQueryRequest request) {
        //防止sql注入
        if (request.getSortField() != null && !request.getSortField().matches("[a-zA-Z_]+")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "非法的排序字段");
        }
        if (request.getPageSize() > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "分页大小不能超过50");
        }
        if (request.getCurrent() < 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "页码不能小于1");
        }

        boolean isAsc;
        if (CommonConstant.SORT_ORDER_ASC.equals(request.getSortOrder())) {
            isAsc = true;
        } else if (CommonConstant.SORT_ORDER_DESC.equals(request.getSortOrder())) {
            isAsc = false;
        } else {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "非法的排序顺序");
        }

        Page<Products> page = new Page<>(request.getCurrent(), request.getPageSize());
        QueryWrapper<Products> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderBy(request.getSortField() != null, isAsc, request.getSortField());
        queryWrapper.eq(request.getCategoryId()!= null, "categoryId", request.getCategoryId());
        queryWrapper.eq(true, "status", 1);
        queryWrapper.like(request.getName()!= null, "name", request.getName());
        // 设置查询条件
        this.page(page, queryWrapper);
        return (Page<ProductsVO>) page.convert(this::convertToVO);
    }

    /**
     * 搜索商品
     *
     * @param keyword 搜索关键词
     * @return Page<ProductsVO> 商品分页列表视图对象
     */
    @Override
    public Page<ProductsVO> searchProducts(String keyword) {
        Page<Products> page = new Page<>(1, 30);
        QueryWrapper<Products> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", keyword);
        this.page(page, queryWrapper);
        return (Page<ProductsVO>) page.convert(this::convertToVO);
    }

    /**
     * 按分类查询商品
     *
     * @param categoryId 分类ID
     * @return Page<ProductsVO> 商品分页列表视图对象
     */
    @Override
    public Page<ProductsVO> getProductsByCategory(Long categoryId) {
        Page<Products> page = new Page<>(1, 30);
        QueryWrapper<Products> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("categoryId", categoryId);
        this.page(page, queryWrapper);
        return (Page<ProductsVO>) page.convert(this::convertToVO);
    }

    /**
     * 获取热门商品列表
     *
     * @return Page<ProductsVO> 商品分页列表视图对象
     */
    @Override
    public Page<ProductsVO> getHotProducts() {
        Page<Products> page = new Page<>(1, 30);
        QueryWrapper<Products> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("sales");
        this.page(page, queryWrapper);
        return (Page<ProductsVO>) page.convert(this::convertToVO);
    }

    /**
     * 获取商品库存
     *
     * @param id 商品ID
     * @return Integer 商品库存数量
     */
    @Override
    public Integer getStock(Long id) {
        Products product = this.getById(id);
        return product != null ? product.getStock() : 0;
    }

    /**
     * 获取商品销量
     *
     * @param productId 商品ID
     * @return Integer 商品销量
     */
    @Override
    public Integer getProductSales(Long productId) {
        Products product = this.getById(productId);
        return product != null ? product.getSales() : 0;
    }

    /**
     * 增加商品销量
     *
     * @param productId 商品ID
     * @param quantity  增加的销量数量
     * @return Boolean 操作是否成功
     */
    @Override
    public Boolean increaseSales(Long productId, Integer quantity) {
        return this.lambdaUpdate()
                .setSql("sales = sales + " + quantity)
                .eq(Products::getId, productId)
                .update();
    }

    /**
     * 将Products实体转换为ProductsVO视图对象
     *
     * @param product 商品实体
     * @return ProductsVO 商品视图对象
     */
    private ProductsVO convertToVO(Products product) {
        // 转换逻辑
        ProductsVO vo = new ProductsVO();
        vo.setId(product.getId());
        vo.setName(product.getName());
        vo.setImageUrl(product.getImageUrl());
        vo.setPrice(product.getPrice());
        vo.setStock(product.getStock());
        vo.setCategoryId(product.getCategoryId());
        vo.setDescription(product.getDescription());
        return vo;
    }

    /**
     * 将Products实体转换为ProductDetailVO详情视图对象
     *
     * @param product 商品实体
     * @return ProductDetailVO 商品详情视图对象
     */
    private ProductDetailVO convertToDetailVO(Products product) {
        // 转换逻辑
        ProductDetailVO vo = new ProductDetailVO();
        vo.setId(product.getId());
        vo.setName(product.getName());
        vo.setDescription(product.getDescription());
        vo.setPrice(product.getPrice());
        vo.setStock(product.getStock());
        vo.setCategoryId(product.getCategoryId());
        return vo;
    }


}




